package com.base.service;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import com.alibaba.fastjson.JSONObject;
import com.base.exception.BusinessException;
import com.base.utils.IpUtil;
import com.base.vo.LoginUserInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @类描述：异步记录日志
 * @创建人：wangdw
 * @创建时间：2019年1月15日 下午4:11:28
 */
@Component
public class AsyncLogRecord {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Async
    public void save(HttpServletRequest request, Object handler, LoginUserInfo userInfo) {
        try {
            if (!(handler instanceof HandlerMethod)) {
                logger.info("请求的不是方法，不记录日志！{}", handler.getClass().getName());
                return;
            }
            // 获取请求信息
            String accessPath = request.getRequestURI();
            String accessIp = IpUtil.getIpAddress(request);
            String params = request.getQueryString();
            if (StringUtils.isBlank(params)) {
                params = JSONObject.toJSONString(request.getParameterMap());
            }
            
            // 组装日志参数 DOTO
            String description = "";// 访问接口名称（利用swagger注解或自定义注解）
            
            HandlerMethod method = (HandlerMethod) handler;
            // 获取类上的swagger描述
            Class<?> clazz = method.getBeanType();
            Api api = clazz.getAnnotation(Api.class);
            if (api != null) {
                description = StringUtils.isNotBlank(api.description()) ? api.description() : api.value();
                if (StringUtils.isBlank(description)) {
                    description = api.tags() != null ? api.tags()[0] : "";
                }
            }
            
            // 获取方法上的swagger描述
            ApiOperation apiOperation = method.getMethodAnnotation(ApiOperation.class);
            if (apiOperation != null) {
                description += "-" + apiOperation.value();
            }
            
            // TODO insertDB
            int ret = 0;
            logger.debug("AsyncLogRecord.save() :{}", ret);
        } catch (Exception e) {
            BusinessException.info("记录日志发生异常", e);
        }
    }
}
